'use strict';
const db = uniCloud.database()
const postsCollection = db.collection('posts')

exports.main = async (event, context) => {
	const { page = 1, pageSize = 10, keyword = '' } = event
	const skip = (page - 1) * pageSize
	
	try {
		let query = {}
		
		// 如果有搜索关键词，添加搜索条件
		if (keyword) {
			query = {
				$or: [
					{
						title: new RegExp(keyword, 'i')
					},
					{
						content: new RegExp(keyword, 'i')
					},
					{
						userName: new RegExp(keyword, 'i')
					}
				]
			}
		}
		
		// 获取帖子总数
		const countResult = await postsCollection.where(query).count()
		const total = countResult.total
		
		// 获取帖子列表
		const result = await postsCollection
			.where(query)
			.orderBy('createTime', 'desc')
			.skip(skip)
			.limit(pageSize)
			.get()
		
		return {
			code: 0,
			msg: '获取成功',
			data: result.data,
			total,
			hasMore: skip + pageSize < total
		}
	} catch (e) {
		return {
			code: -1,
			msg: '获取失败',
			error: e
		}
	}
}; 